package cn.tedu.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.TimeoutException;


public class DirectMode {

    //准备连接对象,连接上rabbitmq ip port(5672)

    private static final String TYPE = "direct";//交换机类型
    private static final String EXNAME = "EX_" + TYPE;

    //声明组件 2个队列 一个交换机,声明绑定关系
    private static final String Q01 = "QUEUE01_" + TYPE;
    private static final String Q02 = "QUEUE02_" + TYPE;
    private Channel channel;

    @Before
    public void initChannel() throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("10.42.77.153");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        Connection connection = factory.newConnection();
        channel = connection.createChannel();
    }

    //声明组件的客户端

    @Test
    public void declare() throws Exception {
        //声明队列
        channel.queueDeclare(Q01, false, false, false, null);
        channel.queueDeclare(Q02, false, false, false, null);
        //声明交换机
        channel.exchangeDeclare(EXNAME, TYPE);
        //声明队列和交换机绑定
        channel.queueBind(Q01, EXNAME, "北京");
        channel.queueBind(Q02, EXNAME, "上海");
        channel.queueBind(Q02, EXNAME, "广州");
    }

    //生产端发送消息
    @Test
    public void producer() throws IOException {
        channel.basicPublish(EXNAME, "新疆", null, "你好啊".getBytes());
    }

}
